package com.aisino.nmg.template.freemarker;

import com.aisino.nmg.constant.GeneratorConstants;
import com.aisino.nmg.template.TemplateEngine;
import freemarker.template.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

@Slf4j
public class FreeMarkerFactory implements TemplateEngine {
    private Configuration config;

    private String classPath;

    private Version freeMarkerVersion = Configuration.VERSION_2_3_28;

    public FreeMarkerFactory(String classPath){
        this.classPath = classPath;
        initConfiguration();
    }

    public void initConfiguration() {
        try {
            config = new Configuration(freeMarkerVersion);
            config.setDirectoryForTemplateLoading(new File(classPath + "templates"+File.separator+"freemarker"+File.separator));
            config.setObjectWrapper(new DefaultObjectWrapper(freeMarkerVersion));

            config.setSetting("classic_compatible", "true");
            config.setSetting("whitespace_stripping", "true");
            config.setSetting("template_update_delay", "1");
            config.setSetting("locale", "zh_CN");
            config.setSetting("default_encoding", GeneratorConstants.DEFAULT_ENCODING);
            config.setSetting("url_escaping_charset", GeneratorConstants.DEFAULT_ENCODING);
            config.setSetting("datetime_format", "yyyy-MM-dd hh:mm:ss");
            config.setSetting("date_format", "yyyy-MM-dd");
            config.setSetting("time_format", "HH:mm:ss");
            config.setSetting("number_format", "0.######;");
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
    }

    @Override
    public void process(Map<String, Object> model, String templateFileName, Writer writer) {
        try {
            Template template = config.getTemplate(templateFileName, GeneratorConstants.DEFAULT_ENCODING);
            template.process(model, writer);
            writer.flush();
            writer.close();
        } catch (TemplateException | IOException e) {
            log.error("解析ftl文件异常:{}", templateFileName, e);
        }
    }
}
